# -*- coding: utf-8 -*-
# ㊎ Author : XMZ
# ㊍ Time : 2022/3/14 10:28
# ㊌ File : pushNotification.py
# ㊋ IDE :  PyCharm
# ㊏
import datetime
import json
import os
import random
import sys
import traceback
from pathlib import Path
import requests
import threading

from publics.packets import local

path = os.path.abspath(__file__)
sys.path.append(str(Path(__file__).absolute().parent.parent.parent))
from core import settings


def pushMessage(project, content):
    # 在新线程中执行 dingtalk
    threading.Thread(target=dingtalk, args=(project, content)).start()
    # threading.Thread(target=dingtalk, args=(value1, value2))
    # threading.Thread(target=dingtalk, kwargs={'param1': value1, 'param2': value2})
    # threading.Thread(target=qw_notif, args=(project, content)).start()


def dingtalk(project, content):
    """
    钉钉消息推送方法
    :param project: 项目名称
    :param content: 消息内容
    :return:
    """
    to_time = f"\n{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}"
    text = f"""{project}-异常：\nIP:{local()}\n消息内容：\n{content}\n{to_time}"""
    data = {
        "at": {
            # "atUserIds": [mobile],
            "atMobiles": [],
            "isAtAll": True
        },
        "text": {"content": text},
        "msgtype": "text"
    }
    api_url = f"https://oapi.dingtalk.com/robot/send?access_token={random.choice(settings.dd_token)}"
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(api_url, data=json.dumps(data), headers=headers)
    return response


def qw_notif(project, content):
    """
    企微消息推送方法
    :param project:项目名称
    :param content:消息内容
    :return:
    """
    to_time = f"\n{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}"
    text = f"""{project}：\nIP:{local()}\n触发时间：{to_time}\n消息内容：\n{content}\n{to_time}"""
    data = {
        "text": {"content": text},
        "msgtype": "text",
        "touser": "@all",
        "safe": 1,
    }
    api_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={random.choice(settings.qw_token)}"
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(api_url, data=json.dumps(data), headers=headers)
    return response


if __name__ == '__main__':
    pro = ""
    con = ""
    pushMessage(project=pro, content=con)
